import knex from '../db/sql'
import {Context, MetheodType, Next} from 'TYPE';
import {parameter, validateBody, validateQuery} from '../parameter_m';
import UserController from './user.controller';
import {notificationDB} from '../db/sqltable/notification.db';
import {userDB} from '../db/sqltable/user.db';

export default class NotificationController {

    @UserController.checkLogin
    @validateQuery({
        paged: 'int?',
        notifications_per_page: 'int?',
        type: 'int?'
    })
    static async getNotification(ctx: Context, next: Next) {
        let {paged, notifications_per_page, type} = ctx.validatedParams
        paged ??= 1
        notifications_per_page ??= 10
        let notifications = await notificationDB.getNotificationByUid(ctx.user.uid, paged, notifications_per_page)
        for(let n of notifications.list){
            switch(n.type){
                case 'message_to':
                case 'message_from':
                    n.user = await userDB.getUserById(Number(n.p1))
                break

            }
        }
        ctx.cd = 0
        ctx.msg = "获取通知成功"
        ctx.return = notifications
        next()
    }

    @UserController.checkLogin
    @validateQuery({
        notification_id: 'int?',
    })
    static async markRead(ctx: Context, next: Next) {
        let {notification_id} = ctx.validatedParams
        let notification = await notificationDB.getNotification(notification_id) as any
        if (notification.uid == ctx.user.uid) {
            await notificationDB.markReadNotification(notification_id)
            ctx.cd = 0
            ctx.msg = "标记已读成功"
            await next()
            return
        }
        ctx.cd = 1
        ctx.msg = "标记失败"
        next()
    }
    @UserController.checkLogin
    @validateBody({
        uid: 'int',
        content: 'string',
    })
    static async sendMessage(ctx: Context, next: Next) {
        let {uid, content} = ctx.validatedParams
        let user = await userDB.getUserById(uid)
        if (!user) {
            ctx.cd = 1
            ctx.msg = "无此用户！！"
            await next()
            return
        }
        if(content.length > 10000){
            ctx.cd = 1
            ctx.msg = "内容太长！！"
            await next()
            return
        }
        if(ctx.user.uid == uid){
            ctx.cd = 1
            ctx.msg = "不支持给自己发消息！！"
            await next()
            return
        }
        notificationDB.addNotification(ctx.user.uid,'message_to',uid,content)
        notificationDB.addNotification(uid,'message_from',String(ctx.user.uid),content)
        ctx.cd = 0
        ctx.msg = "发送成功"
        next()
    }
    
}
